package com.atguigu.gmall;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author: atguigu
 * @create: 2023-03-01 09:07
 */
public class CompletableFutureReturnApplyAsync {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        //1.创建线程A异步操作对象-需求线程A有返回结果
        CompletableFuture<String> futureA = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "\t线程A执行了");
            return "AAA";
        });

        //2.基于上面A异步对象创建线程B的异步操作对象-需求:需要获取A线程结果,在B线程中返回新的结果
        CompletableFuture<String> futureB = futureA.thenApplyAsync(resultA -> {
            System.out.println(Thread.currentThread().getName() + "\t线程B执行了,得到A的结果:" + resultA);
            return "BBB";
        });

        //3.基于上面A异步对象创建线程C的异步操作对象-需求:需要获取A线程结果,在C线程中返回新的结果
        CompletableFuture<String> futureC = futureA.thenApplyAsync(resultA -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "\t线程C执行了,得到A的结果:" + resultA);
            return "CCC";
        });


        CompletableFuture.allOf(futureA, futureB, futureC).join();
        //CompletableFuture.anyOf(futureA, futureB, futureC);

        //4.分别获取B线程 C线程结果
        //String b = futureB.get();
        //System.out.println("线程B执行结果:"+b);
        //String c = futureC.get();
        //System.out.println("线程C执行结果:"+c);

    }
}
